package com.ve.file;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.ve.c51.R;
import com.ve.utils.ThreadPool;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;

public class FileAdapter extends BaseQuickAdapter<GFile, BaseViewHolder> {
    protected ItemListener itemListener;

    public FileAdapter() {
        super(R.layout.item_file, new ArrayList<>());
        setOnItemClickListener((adapter, view, position) -> {toggle(getItem(position),position);});
        setOnItemLongClickListener((adapter, view, position) -> {
            if (itemListener != null) {
                itemListener.onLongClick(view, position, getItem(position));
            }
            return true;
        });
    }

    public void toggle(GFile file, int position) {
        ThreadPool.doThread(() -> {

            if (file.isDirectory()) {
                if (file.isExpand()) {
                    removeChildren(file.getLevel(), position);
                    handler.sendEmptyMessage(NOTIFY_LIST);
                    file.setExpand(false);

                } else {
                    ArrayList<GFile> children = getChildren(file);

                    for (GFile child : children) {
                        initBase(child);
                    }
                    addChildren(children, position);
                    file.setExpand(true);
                    handler.sendEmptyMessage(NOTIFY_LIST);

                    for (GFile child : children) {
                        initThumbnail(child);
                    }
                    handler.sendEmptyMessage(NOTIFY_LIST);
                }


            } else {
                handler.sendMessage(Message.obtain(handler, OPEN_FILE, position, 0));

            }
        });

    }

    public void initBase(GFile child) {
        File file = new File(child.getPath());
        child.type = child.initType();
        child.directory = file.isDirectory();
        child.openable = file.isDirectory() && file.canRead();
        child.size = file.length();
        child.icon = child.isDirectory() ? GFile.ICON_DIR : child.getType() == GFile.TYPE_C ? GFile.ICON_CODE : GFile.ICON_FILE;


    }

    private void initThumbnail(GFile child) {
    }

    private ArrayList<GFile> getChildren(GFile gFile) {
        ArrayList<GFile> list = new ArrayList<>();
        File file = new File(gFile.getPath());
        for (String child : file.list()) {
            list.add(new GFile(gFile, child));
        }
        return list;
    }

    private void addChildren(ArrayList<GFile> children, int position) {
        sort(children);
        getData().addAll(position + 1, children);

    }

    public void addChild(GFile child) {
        initBase(child);
        getData().add(child);
        notifyDataSetChanged();

    }

    private int removeChildren(int level, int position) {
        int count = 0;
        for (Iterator<GFile> ite = getData().listIterator(position + 1); ite.hasNext(); ) {
            GFile file = ite.next();
            if (file.getLevel() > level) {
                ite.remove();
                count++;
            } else {
                break;
            }
        }
        return count;
    }

    public void setItemListener(ItemListener itemListener) {
        this.itemListener = itemListener;
    }

    private static void sort(ArrayList<GFile> list) {
        Collections.sort(list, (p1, p2) -> p1.isDirectory() && !p2.isDirectory() ? -1 :
                !p1.isDirectory() && p2.isDirectory() ? 1 :
                        p1.getName().compareTo(p2.getName()));
    }

    @Override
    protected void convert(BaseViewHolder holder, GFile file) {

        holder.setText(R.id.item_file_name, file.getNameText());


        holder.setImageBitmap(R.id.item_file_icon, file.getIcon());

        holder.getView(R.id.item_file_layout).setPadding(file.getLevel() * 10, 0, 0, 0);

        holder.setVisible(R.id.item_file_size, !file.isDirectory());

        holder.setVisible(R.id.item_file_fold, file.isOpenable());
        holder.getView(R.id.item_file_fold).setRotation(file.isExpand() ? 80 : 0);
        holder.setText(R.id.item_file_size, file.getSizeText());
    }

    private static final int NOTIFY_LIST = 1;
    private static final int OPEN_FILE = 2;

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case NOTIFY_LIST:
                    notifyDataSetChanged();
                    break;
                case OPEN_FILE:
                    if (itemListener != null) {
                        itemListener.onOpen(msg.arg1, getItem(msg.arg1));
                    }
                    break;

            }

        }
    };



    public void reset() {
        for (Iterator<GFile> ite = getData().listIterator(); ite.hasNext(); ) {
            GFile file = ite.next();
            if (file.getLevel() > 0) {
                Log.d(TAG, "reset: "+file.getPath());
                ite.remove();

            } else {
                file.setExpand(false);
            }
        }
        notifyDataSetChanged();
    }


}